package operation;

import User.User;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class SendMessage implements IOperation{

    @Override
    public boolean operate(User user) {
        Scanner in = new Scanner(System.in);
        Socket socket = null;
        OutputStream outputStream = null;
        try {
            int count = 0; //弹幕数
            String data = null;
            System.out.println("请输入对方的IP和Port：");
            //指明服务器端IP和地址
            String ip = in.next();
            int port = in.nextInt();
            in.nextLine(); //过滤回车
            while(true){
                if (count == 5){
                    System.out.println("弹幕发送已达上限，退回功能界面。");
                    return true;
                }
                socket = new Socket(ip, port);
                //获取socket输出流
                outputStream = socket.getOutputStream();
                if(count == 0){
                    System.out.println("键入信息：");
                    data = in.nextLine();
                }
                outputStream.write(data.getBytes()); //传输数据
                socket.shutdownOutput();
                count++;//弹幕+1
                System.out.println("键入信息：");
                data = in.nextLine();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage() + "超过" + (ReceiveMessage.TIME_OUT / 1000) +
                    "秒未发送任何信息，接收端已关闭。");
        }finally {
            //关闭连接资源
            //in.close(); //关闭这个会报错
            try {
                if (socket != null){
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (outputStream != null){
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return true;
    }
}
